<template>
  <el-dialog v-model="visible" title="模型分析数据" width="80%" :before-close="handleClose" class="model-analysis-dialog" append-to-body>
    <div class="analysis-content">
      <div class="chart-container">
        <div ref="chartRef" class="chart" />
      </div>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, onUnmounted, watch, nextTick } from 'vue';
import * as echarts from 'echarts';
import { useIntelligentAnalyticsStore } from '@/store/modules/IntelligentAnalytics/useIntelligentAnalyticsStore';

interface Props {
  modelValue: boolean;
}

interface Emits {
  (event: 'update:modelValue', value: boolean): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

const chartRef = ref<HTMLElement>();
let chartInstance: echarts.ECharts | null = null;
let resizeHandler: (() => void) | null = null;

const visible = ref(false);
const { modelData } = useIntelligentAnalyticsStore();

// 监听 modelValue 变化
watch(
  () => props.modelValue,
  (newVal) => {
    visible.value = newVal;
    if (newVal) {
      nextTick(() => {
        initChart();
      });
    }
  },
  { immediate: true }
);

// 关闭对话框
const handleClose = () => {
  visible.value = false;
  emit('update:modelValue', false);
};

// 初始化图表
const initChart = async () => {
  if (!chartRef.value) return;

  // 销毁已存在的图表实例
  if (chartInstance) {
    chartInstance.dispose();
    chartInstance = null;
  }

  // 创建新的图表实例
  chartInstance = echarts.init(chartRef.value);

  const { time_concentration = [], methane_concentration_by_hour = [], outside_temperature_by_hour = [] } = modelData.value;

  // 处理时间数据，提取小时
  const timeLabels = time_concentration.map((time: string) => {
    const date = new Date(time);
    return `${date.getMonth() + 1}/${date.getDate()} ${date.getHours()}:${date.getMinutes().toString().padStart(2, '0')}`;
  });

  // 配置图表选项
  const option = {
    title: {
      text: '模型分析数据',
      textStyle: {
        color: '#333333',
        fontSize: 20,
        fontWeight: 'bold'
      },
      left: 'center',
      top: 20
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999'
        }
      },
      backgroundColor: 'rgba(0, 0, 0, 0.8)',
      borderColor: '#409eff',
      borderWidth: 1,
      textStyle: {
        color: '#ffffff'
      }
    },
    legend: {
      data: ['甲烷浓度 (ppm)', '外部温度 (°C)'],
      textStyle: {
        color: '#333333'
      },
      top: 60
    },
    grid: {
      top: 120,
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: timeLabels,
        axisPointer: {
          type: 'shadow'
        },
        axisLabel: {
          color: '#333333',
          rotate: 45,
          fontSize: 12
        },
        axisLine: {
          lineStyle: {
            color: '#409eff'
          }
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: '甲烷浓度 (ppm)',
        position: 'left',
        axisLabel: {
          color: '#333333',
          formatter: '{value} ppm'
        },
        axisLine: {
          lineStyle: {
            color: '#409eff'
          }
        },
        splitLine: {
          lineStyle: {
            color: 'rgba(255, 255, 255, 0.2)'
          }
        }
      },
      {
        type: 'value',
        name: '外部温度 (°C)',
        position: 'right',
        axisLabel: {
          color: '#333333',
          formatter: '{value} °C'
        },
        axisLine: {
          lineStyle: {
            color: '#409eff'
          }
        },
        splitLine: {
          show: false
        }
      }
    ],
    series: [
      {
        name: '甲烷浓度 (ppm)',
        type: 'line',
        yAxisIndex: 0,
        data: methane_concentration_by_hour,
        itemStyle: {
          color: '#FF6B6B'
        },
        lineStyle: {
          color: '#FF6B6B',
          width: 3
        },
        symbol: 'circle',
        symbolSize: 8,
        emphasis: {
          focus: 'series',
          itemStyle: {
            borderColor: '#fff',
            borderWidth: 2
          }
        },
        markPoint: {
          data: [
            { type: 'max', name: '最大值' },
            { type: 'min', name: '最小值' }
          ],
          itemStyle: {
            color: '#FF6B6B'
          },
          label: {
            color: '#333333'
          }
        }
      },
      {
        name: '外部温度 (°C)',
        type: 'line',
        yAxisIndex: 1,
        data: outside_temperature_by_hour,
        itemStyle: {
          color: '#4ECDC4'
        },
        lineStyle: {
          color: '#4ECDC4',
          width: 3
        },
        symbol: 'diamond',
        symbolSize: 8,
        emphasis: {
          focus: 'series',
          itemStyle: {
            borderColor: '#fff',
            borderWidth: 2
          }
        },
        markPoint: {
          data: [
            { type: 'max', name: '最大值' },
            { type: 'min', name: '最小值' }
          ],
          itemStyle: {
            color: '#4ECDC4'
          },
          label: {
            color: '#333333'
          }
        }
      }
    ]
  };

  // 设置图表选项
  chartInstance.setOption(option);

  // 监听窗口大小变化
  resizeHandler = () => {
    if (chartInstance) {
      chartInstance.resize();
    }
  };

  window.addEventListener('resize', resizeHandler);
};

// 组件销毁时清理
onUnmounted(() => {
  // 清理resize事件监听器
  if (resizeHandler) {
    window.removeEventListener('resize', resizeHandler);
    resizeHandler = null;
  }

  // 清理图表实例
  if (chartInstance) {
    chartInstance.dispose();
    chartInstance = null;
  }
});
</script>

<style scoped lang="scss">
.model-analysis-dialog {
  :deep(.el-dialog) {
    background: linear-gradient(270deg, rgba(9, 48, 111, 0.9) 0%, rgba(9, 48, 111, 0.95) 100%);
    border: 1px solid #409eff;
    border-radius: 8px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
  }

  :deep(.el-dialog__header) {
    background: linear-gradient(90deg, #409eff 0%, #67c23a 100%);
    padding: 15px 20px;
    border-radius: 8px 8px 0 0;

    .el-dialog__title {
      color: #ffffff;
      font-size: 18px;
      font-weight: bold;
    }

    .el-dialog__headerbtn {
      .el-dialog__close {
        color: #ffffff;
        font-size: 20px;

        &:hover {
          color: #f56c6c;
        }
      }
    }
  }

  :deep(.el-dialog__body) {
    padding: 20px;
    background: transparent;
  }
}

.analysis-content {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.chart-container {
  flex: 1;
  min-height: 500px;
  display: flex;
  justify-content: center;
  align-items: center;

  .chart {
    width: 100%;
    height: 500px;
    min-height: 500px;
  }
}

// 滚动条样式
:deep(::-webkit-scrollbar) {
  width: 6px;
}

:deep(::-webkit-scrollbar-track) {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 3px;
}

:deep(::-webkit-scrollbar-thumb) {
  background: rgba(255, 255, 255, 0.3);
  border-radius: 3px;

  &:hover {
    background: rgba(255, 255, 255, 0.5);
  }
}
</style>
